<?php
class NVL_ImgUpload{
    
    var $file_size = 2; //MB
    var $file_type = array('jpg','png','jpeg','gif');
    
    public  function doUpload($path_home,$path_dir,$file,$name,$name_show){
        $ful_path = $path_home.'/'.$path_dir;
        $uploadOk = 1;
        $result = array();
        $message = array();
        $imageFileType = pathinfo($file['name'],PATHINFO_EXTENSION);
        
		$name = $name.'.'.$imageFileType;
		$target_file = $ful_path.'/'. $name;
        // Check if image file is a actual image or fake image
        $check = getimagesize($file["tmp_name"]);
        if($check == false) {
            $message[] =  $name_show." - File không phải là hình ảnh.";
            $uploadOk = 0;
        } 
        // Allow certain file formats
        if( !in_array($imageFileType, $this->file_type ) && $uploadOk)
        {
            $message[] = $name_show." - Chỉ ".implode(" , ",$this->file_type)." mới được tải lên.";
            $uploadOk = 0;
        }
        
        
        // Check file size
        if ($file["size"] > ($this->file_size *(1024*1024)) && $uploadOk) {
            $message[] =  $name_show." - File của bạn lớn hơn ".$this->file_size.' MB';
            $uploadOk = 0;
        }
        
        // Check if file already exists
        if (file_exists($target_file) && $uploadOk) {
            //$message[] =  $name_show." - Ảnh này đã được tải lên.";
            //$uploadOk = 0;
        }
        
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            //$message[] = "Sorry, your file was not uploaded.";
            $result['status'] = 'error';
            // if everything is ok, try to upload file
        } else {
            if (!file_exists($ful_path)) {
                mkdir($ful_path, 0755, true);
            }
            if (move_uploaded_file($file['tmp_name'], $target_file)) {
                $message[] = "The file ". basename( $file["name"]). " has been uploaded.";
                $result['status'] = 'success';
				$result['path'] = $path_dir.$name;
                
            } else {
                $result['status'] = 'error';
                $message[] = $name_show ." - Sorry, there was an error uploading your file.";
                //$message[] = $ful_path;
                //$message[] = $name;
            }
        }
        $result['message'] = $message;
        return $result;
    }
}